# TabBrowser module
module ObjectiveKyusu::WebBrowser
  module TabBrowser
    def self.included(base)
      base.send(:include, TabBrowserInstanceMethods)
      base.send(:extend, TabBrowserClassMethods)
    end

    # === Tab配列クラス
    class Tabs < Array
      @@default_tab_size = 1
      def initialize()
        super(@@default_tab_size){Tab.new}
      end

      # === タブの追加
      def add_tab(url = "")
        self << Tab.new(tabs_instance: self, url: url)
      end

      alias remove_tab :delete_at
    end

    # === タブクラス
    class Tab
      @@accessors = [:url, ]
      attr_accessor :tabs_instance, *@@accessors
      def initialize(attr = {})
        @tabs_instance = attr[:tabs_instance]
        @@accessors.each do |k|
          self.instance_variable_set(:"@#{k}", attr[k])
        end
      end

      # === INDEX
      def index
        self.tabs_instance.map(&:object_id).index(self.object_id)
      end

      # === リンク選択時
      def select_link(url)
        if self.url_histories.size != (self.history_index + 1)
          # 現在表示している画面が履歴の先頭以外の場合、その先を削除
          self.url_histories = self.url_histories[0, self.history_index]
        end
        self.url_histories << [self.current_url]
        self.history_index += 1
        self.current_uri = url
      end

      # === 戻るボタン押下時
      def browser_back(index = nil)
        index ||= self.history_index - 1
        unless self.url_histories[index].nil?
          self.history_index = index
          self.current_uri = self.url_histories[index]
        end
      end

      # === 進むボタン押下時
      def browser_forward(index = nil)
        index ||= self.history_index + 1
        unless self.url_histories[index].nil?
          self.history_index = index
          self.current_uri = self.url_histories[index]
        end
      end
    end
  end

  # === class methods
  module TabBrowserClassMethods

  end

  # === instance methods
  module TabBrowserInstanceMethods

  end
end